from rest_framework import filters

from django.shortcuts import get_object_or_404
from rest_framework import viewsets, status, permissions
from rest_framework.decorators import action
from rest_framework.generics import get_object_or_404
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from django.db import connection, transaction, models

from user.models import User, Role, Clazz, Menu, Func, Language, Module, Permission, Task, TaskUser, Group
from user.seriaizers import LanguageSerializers, CustomPageNumberPagination, MenuSerializer, FuncSerializer, \
    ClazzSerializers, PermissionSerializer, TaskCompletionSerializer, DifficultyLevelSerializer, TaskStatusSerializer, \
    ClassCountSerializer, StudentManageSerializer, StudentCreateSerializer
from user.seriaizers import (
    StudentSerializer,
    UserSerializer,
    UserStatusSerializer,
    RoleSerializer,
    ClazzSerializer,
    LanguageSerializer,
    MenuSerializer,
    FuncSerializer,
    ModuleSerializer,
    UserSerializers,
    CustomPageNumberPagination, TaskManageSerializer,
)
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.permissions import IsAuthenticated
from django.utils import timezone

from user.seriaizers import UserSerializer, RoleSerializer, ClazzSerializer, UserSerializers,ModuleSerializer,LanguageSerializer
from rest_framework.permissions import IsAuthenticated
from django.db.models import Value, F,Count

import datetime


class StudentViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]
    queryset = User.objects.filter(is_delete=False, is_staff=False)
    serializer_class = UserSerializer
    pagination_class = PageNumberPagination
    PageNumberPagination.page_size_query_param = "rows"

    filter_backends = [DjangoFilterBackend, filters.SearchFilter]
    filterset_fields = ['name','clazz_name', 'is_active']
    search_fields = ['name']

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = StudentSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = StudentSerializer(queryset, many=True)
        return Response(serializer.data)

    @action(methods=['patch'], detail=True, url_path='update-status')
    def update_status(self, request, pk=None):
        user = self.get_object()
        serializer = UserStatusSerializer(user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({'msg': '更新成功'}, status=status.HTTP_200_OK)

    @action(methods=['post'], detail=True, url_path='reset-password')
    def reset_password(self, request, pk=None):
        print("reset_password called", request.user, request.auth)
        user = self.get_object()
        user.set_password('123456')
        user.save()
        return Response({'msg': '密码已重置为 123456'}, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='delete-status')
    def delete_status(self, request, pk=None):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.filter(is_delete=False, is_staff=True,)

    serializer_class = UserSerializer

    pagination_class = PageNumberPagination

    PageNumberPagination.page_size_query_param = "rows"

    def create(self, request, *args, **kwargs):

        # 接收页码传入的数据
        serializer = self.get_serializer(data=request.data)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        # 对page 对象进行序列化操作
        serializer = UserSerializers(page, many=True, excludes=['password'])

        # 返回 分页后的结果
        return self.get_paginated_response(serializer.data)

    @action(methods=['GET'], detail=False, url_path='find-role-clazz-list', url_name='find-role-clazz-list')
    def find_role_clazz_list(self, request, *args, **kwargs):

        # 查询所有的角色信息
        role_queryset = Role.objects.filter(is_delete=False, state=True)

        # 查询所有的班级信息
        class_queryset = Clazz.objects.filter(is_delete=False, state=True)

        role_serializer = RoleSerializer(role_queryset, many=True, fields=["id", "name"])
        class_serializer = ClazzSerializer(class_queryset, many=True, fields=["id", "name"])

        data = {
            "roleList": role_serializer.data,
            "clazzList": class_serializer.data
        }

        return Response(data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)


class RoleViewSet(viewsets.ModelViewSet):

    queryset = Role.objects.filter(is_delete=False)

    serializer_class = RoleSerializer

    pagination_class = PageNumberPagination

    PageNumberPagination.page_size_query_param = "rows"

    def create(self, request, *args, **kwargs):
        # 接收页码传入的数据
        serializer = self.get_serializer(data=request.data)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)


# 语言视图
class LanguageViewSet(viewsets.ModelViewSet):
    queryset = Language.objects.filter(is_delete=False).order_by('-id')  # 添加排序
    serializer_class = LanguageSerializer
    pagination_class = CustomPageNumberPagination  # 使用自定义分页类
    PageNumberPagination.page_size_query_param = "rows"
    permission_classes = [IsAuthenticated]

    def create(self, request, *args, **kwargs):
        # 接收前端传入的数据
        serializer = self.get_serializer(data=request.data)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 设置创建者和创建时间
        serializer.validated_data['user'] = request.user.username
        serializer.validated_data['create_time'] = timezone.now()
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    def update(self, request, *args, **kwargs):
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        # 设置更新时间
        serializer.validated_data['update_time'] = timezone.now()
        self.perform_update(serializer)
        return Response(serializer.data)

    def get_paginate_by(self, queryset):
        return self.request.query_params.get('rows', self.paginate_by)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        language = self.get_object()
        is_active = request.data.get('is_active')

        if is_active is None:
            return Response(
                {'detail': 'is_active 字段是必填项'},
                status=status.HTTP_400_BAD_REQUEST
            )

        language.is_active = is_active
        language.update_time = timezone.now()
        language.save()

        serializer = self.get_serializer(language)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        language = self.get_object()
        is_delete = request.data.get('is_delete')

        if is_delete is None:
            return Response(
                {'detail': 'is_delete 字段是必填项'},
                status=status.HTTP_400_BAD_REQUEST
            )

        language.is_delete = is_delete
        language.delete_time = timezone.now() if is_delete else None
        language.save()

        serializer = self.get_serializer(language)
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['get'], detail=False, url_path='deleted', url_name='deleted')
    def get_deleted_languages(self, request, *args, **kwargs):
        queryset = Language.objects.filter(is_delete=True)
        page = self.paginate_queryset(queryset)
        serializer = self.get_serializer(page, many=True)
        return self.get_paginated_response(serializer.data)

    @action(methods=['put'], detail=True, url_path='restore', url_name='restore')
    def restore_language(self, request, *args, **kwargs):
        language = self.get_object()
        if not language.is_delete:
            return Response(
                {'detail': '该语言未被删除'},
                status=status.HTTP_400_BAD_REQUEST
            )

        language.is_delete = False
        language.delete_time = None
        language.save()

        serializer = self.get_serializer(language)
        return Response(serializer.data, status=status.HTTP_200_OK)

class MenuViewSet(viewsets.ModelViewSet):

    queryset = Menu.objects.filter(is_delete=False)

    serializer_class = MenuSerializer

    pagination_class = PageNumberPagination

    PageNumberPagination.page_size_query_param = "rows"

    def create(self, request, *args, **kwargs):
        # 接收页码传入的数据
        serializer = self.get_serializer(data=request.data)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

class ModuleViewSet(viewsets.ModelViewSet):
    permission_classes = [IsAuthenticated]

    # 自定义分页类
    class ModulePagination(PageNumberPagination):
        page_size_query_param = "page_size"  # 匹配前端参数名

    pagination_class = ModulePagination  # 替换原有分页设置
    # ...其他代码保持不变
    queryset = Module.objects.filter(is_delete=False)
    serializer_class = ModuleSerializer

    def get_queryset(self):
        queryset = super().get_queryset()
        # 添加过滤条件
        lang_id = self.request.query_params.get('langId')
        if lang_id:
            queryset = queryset.filter(language_id=lang_id)
        return queryset.order_by('sort', 'id')

    def perform_create(self, serializer):
        serializer.save(user=self.request.user.username)

    def perform_update(self, serializer):
        serializer.save(user=self.request.user.username, update_time = timezone.now())

    @action(methods=['GET'], detail=False)
    def get_languages(self, request):
        languages = Language.objects.filter(is_delete=False, is_active=True)
        serializer = LanguageSerializers(
            languages,
            many=True,
            #  fields=['id', 'name','is_active'])
            context={'request': request})
        return Response(serializer.data)

    # 在ModuleViewSet中重写destroy方法
    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_delete = True
        instance.delete_time = timezone.now()
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

class ClazzViewSet(viewsets.ModelViewSet):

    queryset = Clazz.objects.filter(is_delete=False)

    serializer_class = ClazzSerializers

    pagination_class = PageNumberPagination

    PageNumberPagination.page_size_query_param = "rows"

    def create(self, request, *args, **kwargs):
        print("当前登录用户：", request.user)
        print("真实姓名：", request.user.name)

        data = request.data.copy()
        print("最终传入序列化器的数据:", data)

        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        # ✅ 手动传入 creator 参数（即使字段是只读，也能保存）
        serializer.save(creator=request.user.name)

        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)


class FuncViewSet(viewsets.ModelViewSet):
    queryset = Func.objects.filter(is_delete=False)

    serializer_class = FuncSerializer

    pagination_class = PageNumberPagination

    PageNumberPagination.page_size_query_param = "rows"

    def create(self, request, *args, **kwargs):
        # 接收页码传入的数据
        serializer = self.get_serializer(data=request.data)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)


class PermissionViewSet(viewsets.ViewSet):

    # 获取指定角色权限
    @action(methods=['get'], detail=False, url_path='role/(?P<role_id>[^/.]+)')
    def get_role_permissions(self, request, role_id=None):
        role = get_object_or_404(Role, id=role_id, is_delete=False)

        # 查询该角色的权限，示例假设Permission模型字段名为role、menu、func
        permissions = Permission.objects.filter(role_id=role).values('menu_id', 'func_id')

        # 返回权限列表
        return Response({'permissions': list(permissions)}, status=status.HTTP_200_OK)

    # 保存指定角色的权限
    @action(methods=['post'], detail=False, url_path='role/(?P<role_id>[^/.]+)/save')
    def save_permissions(self, request, role_id=None):
        role = get_object_or_404(Role, id=role_id, is_delete=False)

        permissions_data = request.data.get('permissions', [])

        if not isinstance(permissions_data, list):
            return Response({'detail': 'permissions 应为列表类型'}, status=status.HTTP_400_BAD_REQUEST)

        # 删除该角色原有权限
        Permission.objects.filter(role_id=role).delete()

        # 创建新权限
        new_permissions = []
        for item in permissions_data:
            menu_id = item.get('menu_id')
            func_id = item.get('func_id')

            if menu_id and func_id:
                try:
                    menu = Menu.objects.get(id=menu_id, is_delete=False)
                    func = Func.objects.get(id=func_id, is_delete=False)
                    new_permissions.append(Permission(role_id=role, menu_id=menu, func_id=func))
                except Menu.DoesNotExist:
                    return Response({'detail': f'菜单 ID {menu_id} 不存在'}, status=status.HTTP_400_BAD_REQUEST)
                except Func.DoesNotExist:
                    return Response({'detail': f'功能模块 ID {func_id} 不存在'}, status=status.HTTP_400_BAD_REQUEST)

        Permission.objects.bulk_create(new_permissions)

        return Response({'detail': '权限保存成功'}, status=status.HTTP_200_OK)

    @action(methods=["GET"], detail=False, url_path='menus', url_name='menus')
    def find_menu_funcs_list(self, request, *args, **kwargs):

        # 获取当前登录的 角色
        role = request.user.role

        if role is None and request.user.is_superuser:
            # 查询所有未删除菜单和功能
            menus = Menu.objects.filter(is_delete=False).annotate(
                menu_id=F("id"),
                pid=Value("", output_field=models.CharField()),
                name=F("menu_name")
            ).values("menu_id", "pid", "icon", "name")

            funcs = Func.objects.filter(is_delete=False).annotate(
                func_id=F("id"),
                pid=F("menu_id"),
                name=F("func_url"),
                title=F("func_name")
            ).values("func_id", "pid", "name", "title")
        else:
            menus = Permission.objects.values("menu_id").annotate(pid=Value("")).annotate(
                icon=F("menu_id__icon")).annotate(name=F("menu_id__menu_name")).filter(role_id=role).distinct()

            funcs = Permission.objects.values("func_id").annotate(pid=F("menu_id")).annotate(
                name=F("func_id__func_url")).annotate(title=F("func_id__func_name")).filter(role_id=role).distinct()
        # print(menus, funcs)

        # 组装菜单数据
        menu_dict = {}
        for menu in menus:
            menu_id = str(menu['menu_id'])
            menu_dict[menu_id] = {
                "index": menu_id,
                'title': menu['name'],
                'icon': menu['icon'],
                'children': []
            }

        # 为每个菜单添加子功能
        for func in funcs:
            menu_id = str(func['pid'])
            if menu_id in menu_dict:
                menu_dict[menu_id]['children'].append({
                    'title': func['title'],
                    'name': func['name'],
                })
        # 将字典转换为列表并排序
        result = sorted(menu_dict.values(), key=lambda x: int(x['index']))

        return Response(result, status=status.HTTP_200_OK)


class CustomPagination(PageNumberPagination):
    page_size = 10
    page_size_query_param = 'rows'  # 前端传递的参数名
    page_query_param = 'page'  # 页码参数名
    max_page_size = 100

    def get_paginated_response(self, data):
        return Response({
            'count': self.page.paginator.count,
            'results': data,
            'page': self.page.number,
            'pages': self.page.paginator.num_pages,
        })


# 任务管理
class TaskViewSet(viewsets.ModelViewSet):
    queryset = Task.objects.filter(is_delete=False).order_by('-create_time')  # 添加排序
    serializer_class = TaskManageSerializer
    pagination_class = CustomPagination  # 使用自定义分页类

    def create(self, request, *args, **kwargs):
        # 接收页码传入数据
        serializer = self.get_serializer(data=request.data)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库中
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    @action(methods=['put'], detail=True, url_path='delete-status', url_name='delete-status')
    def delete_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200_OK)

    @action(methods=['put'], detail=True, url_path='update-status', url_name='update-status')
    def update_status(self, request, *args, **kwargs):
        user = self.get_object()
        serializer = self.get_serializer(user, data=request.data, partial=True)
        # 校验数据
        serializer.is_valid(raise_exception=True)
        # 保存到数据库
        serializer.save()
        return Response(serializer.data, status=status.HTTP_200)

    def get_queryset(self):
        queryset = super().get_queryset()
        # 添加筛选功能
        title = self.request.query_params.get('title', None)  # 改为title
        completed = self.request.query_params.get('completed', None)
        lang_id = self.request.query_params.get('language_id', None)  # 改为lang_id
        module_id = self.request.query_params.get('module_id', None)  # 改为module_id
        if title:
            queryset = queryset.filter(title__icontains=title)
        if completed:
            queryset = queryset.filter(completed=completed)
        if lang_id:
            queryset = queryset.filter(language_id=lang_id)
        if module_id:
            queryset = queryset.filter(module_id=module_id)

        return queryset.order_by('-create_time')

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        instance.is_delete = True
        instance.delete_time = timezone.now()
        instance.save()
        return Response(status=status.HTTP_204_NO_CONTENT)

class ClassCountViewSet(viewsets.ViewSet):
    def list(self, request):
        classes = Clazz.objects.filter(is_delete=False)
        serializer = ClassCountSerializer(classes, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)


class TaskCompletionViewSet(viewsets.ViewSet):
    def list(self, request):
        classes = Clazz.objects.filter(is_delete=False)
        data = []
        for clazz in classes:
            users = clazz.users.filter(is_delete=False)
            total = users.count()
            completed = TaskUser.objects.filter(user__in=users, status=5).count()
            data.append({
                'clazz_name': clazz.name,
                'total_users': total,
                'completed_tasks': completed,
            })
        # print(data)
        return Response(data)


class DifficultyLevelViewSet(viewsets.ViewSet):
    def list(self, request):
        difficulty_levels = ['简单题', '中等题', '困难题']
        data = []
        for level in difficulty_levels:
            count = Task.objects.filter(completed=level).count()
            data.append({
                'difficulty': level,
                'taskCount': count
            })
        return Response(data)


class TaskStatusViewSet(viewsets.ViewSet):
    def list(self, request):
        # 作业状态映射
        status_map = {
            0: '未开始',
            1: '进行中',
            3: '已提交',
            4: '已检查',
            5: '已完成',
            -1: '异常题',
        }

        queryset = (
            TaskUser.objects
            .filter(user__is_delete=False, user__clazz__is_delete=False)  # 加上过滤逻辑删除
            .values('user__clazz__name', 'status')
            .annotate(count=Count('id'))
        )

        data = []
        for item in queryset:
            data.append({
                'className': item['user__clazz__name'],
                'status': status_map.get(item['status'], '未知状态'),
                'count': item['count'],
            })

        return Response(data)


class HomeStatsViewSet(viewsets.ViewSet):

    def list(self, request):
        # 统计逻辑
        total_users = User.objects.filter(is_delete=False).count()
        total_clazzes = Clazz.objects.filter(is_delete=False).count()
        total_tasks = Task.objects.filter(is_delete=False).count()
        total_task_user = TaskUser.objects.count()
        total_groups = Group.objects.count()

        data = {
            "total_users": total_users,
            "total_clazzes": total_clazzes,
            "total_tasks": total_tasks,
            "total_task_user": total_task_user,
            "total_groups": total_groups,
        }
        return Response(data)


class ClassStatisticsViewSet(viewsets.ViewSet):

    @action(detail=False, methods=['get'], url_path='statistics')
    def class_statistics(self, request):
        now = timezone.now()
        year = now.year

        first_half_start = datetime.datetime(year, 1, 1)
        first_half_end = datetime.datetime(year, 6, 30, 23, 59, 59)
        second_half_start = datetime.datetime(year, 7, 1)
        second_half_end = datetime.datetime(year, 12, 31, 23, 59, 59)

        first_half_data = (
            User.objects.filter(create_time__range=(first_half_start, first_half_end))
            .values("clazz__name")
            .annotate(user_count=Count("id"))
        )

        second_half_data = (
            User.objects.filter(create_time__range=(second_half_start, second_half_end))
            .values("clazz__name")
            .annotate(user_count=Count("id"))
        )

        result = {
            "first_half": list(first_half_data),
            "second_half": list(second_half_data),
        }
        return Response(result)




class StudentManageViewSet(viewsets.ViewSet):
    queryset = User.objects.filter(is_delete=False,is_staff=False).order_by('-date_joined')
    serializer_class = StudentManageSerializer
    pagination_class = CustomPagination
    filterset_fields = ['name', 'clazz__name', 'is_active']

    def get_serializer_class(self):
        if self.action == 'create':
            return StudentCreateSerializer
        return self.serializer_class

    def get_serializer(self, *args, **kwargs):
        serializer_class = self.get_serializer_class()
        kwargs.setdefault('context', {'request': self.request})
        return serializer_class(*args, **kwargs)

    def get_object(self):
        queryset = self.queryset
        pk = self.kwargs.get('pk')
        obj = get_object_or_404(queryset, pk=pk)
        return obj

    def list(self, request):
        queryset = self.queryset
        # 过滤条件（注意参数名）
        name = request.query_params.get('name')
        if name:
            queryset = queryset.filter(name__icontains=name)

        clazz_name = request.query_params.get('clazz_name')  # 前端传clazz_name
        if clazz_name:
            queryset = queryset.filter(clazz__id__icontains=clazz_name)

        is_active = request.query_params.get('is_active')
        if is_active:
            queryset = queryset.filter(is_active=is_active in ['1', 'true'])

        # 分页处理
        paginator = self.pagination_class()
        page = paginator.paginate_queryset(queryset, request)
        serializer = self.get_serializer(page, many=True)
        return paginator.get_paginated_response(serializer.data)

    @action(detail=True, methods=['put'], url_path='update-state')
    def update_status(self, request, pk=None):
        student = self.get_object()
        is_active = request.data.get('is_active')

        if is_active is None:
            return Response(
                {'detail': 'is_active 字段是必填项'},
                status=status.HTTP_400_BAD_REQUEST
            )

        student.is_active = is_active
        student.save()
        return Response({'detail': '状态更新成功'})

    @action(detail=True, methods=['put'], url_path='reset-password')
    def reset_password(self, request, pk=None):
        student = self.get_object()
        new_password = request.data.get('password', '123456')
        student.set_password(new_password)
        student.save()
        return Response({'detail': '密码重置成功'})

    @action(detail=True, methods=['delete'], url_path='delete-state')
    def soft_delete(self, request, pk=None):
        try:
            student = self.get_object()
            student.is_delete = True
            student.delete_time = timezone.now()
            student.save()
            return Response({'detail': '删除成功'}, status=status.HTTP_200_OK)
        except Exception as e:
            return Response({'detail': f'删除失败: {str(e)}'}, status=status.HTTP_400_BAD_REQUEST)


class ClazzsViewSet(viewsets.ModelViewSet):
    queryset = Clazz.objects.filter(is_delete=False)
    serializer_class = ClazzSerializer
    def list(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

